<template>
  <div id="app" style="margin-bottom: 200px;">
    <h3>排期id配置&nbsp;&nbsp;&nbsp;pid:{{listQuery.project}}</h3>
    <el-tabs v-model="event_type" @tab-click="handleClick">
      <el-tab-pane label="联盟使命" name="0"></el-tab-pane>
      <el-tab-pane label="个人活动" name="2"></el-tab-pane>
      <el-tab-pane label="地狱活动" name="1"></el-tab-pane>
    </el-tabs>
    <div>
      <div style="width: 40%;float: left;">
        场次规则(每轮时长 s)(0表示空排期)：<el-input placeholder="请输入内容" v-model.number="basic_data[event_type].cycle" v-if="basic_data[event_type]"> </el-input>
        <el-divider></el-divider>

        <el-table :data="basic_data[event_type].pid_list"  style="width: 100%" :row-class-name="tableRowClassName" v-if="basic_data[event_type]">
            <el-table-column align="center" label="每轮循环内pid顺序" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.$index+1 }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="pid" >
                <template slot-scope="scope">
                  <el-select v-model.number="scope.row.pid">
                    <el-option v-for="item in project_pid_list[event_type]"
                      :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="deletePidItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="reward_button-setting" style="margin-top: 20px;">
            <el-button type="success" @click="addPidItem">新 增</el-button>
            <el-button type="warning" @click="genPidItem">生 成</el-button>
          </div>
      </div>

      <div style="width: 50%;float: left;margin-left: 50px;">
        结果：<el-input placeholder="结果" disabled> </el-input>
        <el-divider></el-divider>
        <el-table ref="dragTable" :data="basic_data[event_type].cycle_pid_list" highlight-current-row style="width: 100%" row-key="idx" v-if="basic_data[event_type]">
            <el-table-column align="center" label="场次" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.$index+1 }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="pid" >
                <template slot-scope="scope">
                  <el-select v-model.number="scope.row.pid">
                    <el-option v-for="item in project_pid_list[event_type]"
                      :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="deleteCidItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="reward_button-setting" style="margin-top: 20px;">
            <el-button type="success" @click="addCidItem">新 增</el-button>
          </div>

      </div>
      <div style="margin: 0 auto;width: 500px;">
        <el-button type="primary" @click="onSubmit('basic_data')">提交</el-button>
      </div>

    </div>


  </div>
</template>

<script>
  import { fetchList} from '@/api/index'
  import Sortable from 'sortablejs'
  export default {
    name: 'extreme_user_event_schedule',
    data() {
      return {
        listQuery: {
          'action': 'extreme_user_event_schedule',
          'project': 0,
          'type': '',
          'data': null
        },
        listLoading: true,
        basic_data: {},
        project_pid_list:[],
        event_type:'0',
        rules: {
        }
      }
    },
    created() {
      this.listQuery.project = this.$route.query.project
      this.getList()
    },
    methods: {
      async getList() {
        this.listLoading = true;
        this.listQuery.type = 'basic'
        await fetchList(this.listQuery).then(response => {
          this.basic_data = response.data
          this.project_pid_list = response.pid_list
          this.listLoading = false
        })
        this.$nextTick(() => {
          this.setSort()
        })
      },
      handleClick(){

      },
      deletePidItem(index){
        this.basic_data[this.event_type].pid_list.splice(index, 1)
      },
      addPidItem(){
        this.basic_data[this.event_type].pid_list.push({})
      },
      genPidItem(){
        if(this.basic_data[this.event_type].cycle !== 0 && this.basic_data[this.event_type].pid_list.length === 0){
          this.$notify.error({
            title: '错误',
            message: '每轮循环内pid不能为空'
          });
          return false
        }
        for (let i = 0; i < this.basic_data[this.event_type].pid_list.length; i++) {
          var node = this.basic_data[this.event_type].pid_list[i]
          if (node['pid'] === undefined || node['pid'] === ''){
            this.$message({'type': 'error', 'message': `循环的第${i+1}条配置的pid为空`});
            return false
          }
        }
        if (this.basic_data[this.event_type].cycle !== 0) {
          var cnt = 1440 / (this.basic_data[this.event_type].cycle / 60)
          if(Number.isInteger(cnt)){
            this.basic_data[this.event_type].cycle_pid_list = []
            while (cnt > 0){
              for (let i = 0; i < this.basic_data[this.event_type].pid_list.length; i++) {
                this.basic_data[this.event_type].cycle_pid_list.push({"pid":this.basic_data[this.event_type].pid_list[i]['pid'],"idx":cnt})
                cnt = cnt -1
              }
            }
          }else{
            this.$notify.error({
              title: '错误',
              message: '每轮时长不可被1天整除'
            });
          }
        }else{
          this.basic_data[this.event_type].pid_list = []
          this.basic_data[this.event_type].cycle_pid_list = []
        }

      },
      deleteCidItem(index){
        this.basic_data[this.event_type].cycle_pid_list.splice(index, 1)
      },
      addCidItem(){
        this.basic_data[this.event_type].cycle_pid_list.push({})
      },
      onSubmit(){
        let permit_submit = this.checkData();
        if (!permit_submit) {
            return
        };
        this.listQuery.type = 'update_basic';
        this.listQuery.data = this.basic_data;
        fetchList(this.listQuery).then(response => {
          if (response.code === 200) {
            this.getList()
            this.$notify({
              title: 'Success',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: response.msg
            });
          }
        })
        return false;
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      checkData(){
        if (this.basic_data[this.event_type].cycle === 0) {
          return true
        }
        for (let i = 0; i < this.basic_data[this.event_type].cycle_pid_list.length; i++) {
          var node = this.basic_data[this.event_type].cycle_pid_list[i]
          if (node['pid'] === undefined || node['pid'] === ''){
            this.$message({'type': 'warning', 'message': `结果第${i+1}条配置的pid为空`});
            return false
          }
        }
        var cnt = 1440 / (this.basic_data[this.event_type].cycle / 60)
        if (this.basic_data[this.event_type].cycle_pid_list.length !== cnt) {
          this.$message({'type': 'error', 'message': '场次数量不等于场次规则计算的值:' + cnt});
          return false
        }

        return true
      },
      setSort() {
        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
          setData: function(dataTransfer) {
            dataTransfer.setData('Text', '')
          },
          onEnd: evt => {
            const targetRow = this.basic_data[this.event_type].cycle_pid_list.splice(evt.oldIndex, 1)[0]
            this.basic_data[this.event_type].cycle_pid_list.splice(evt.newIndex, 0, targetRow)
          }
        })
      },
    }
  }
</script>

<style scoped>
  #app {
    margin: 0 auto;
    width: 70%;
    height: 750px;
  }
</style>
